import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
import Layout from '@/views/Layout'

const routes = [
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    children: [
      {
        // 默认展示的二级路由
        path: '/',
        name: 'Home',
        component: () => import(/* webpackChunkName: "about" */ '../views/Home')
      },
      {
        path: '/category/:id',
        name: 'Category',
        component: () => import(/* webpackChunkName: "about" */ '@/views/Category/index.vue')
      },
      {
        path: '/category/sub/:id',
        name: 'Sub',
        component: () => import(/* webpackChunkName: "about" */ '@/views/Category/sub.vue')
      },
      {
        path: '/goods/:id',
        name: 'Goods',
        component: () => import(/* webpackChunkName: "about" */ '@/views/Goods/index.vue')
      },
      {
        path: '/cart',
        name: 'cart',
        component: () => import('../views/Cart/index.vue')
      },
      {
        path: '/member/checkout',
        name: 'checkout',
        component: () => import('../views/Member/checkout.vue')
      },
      {
        path: '/member/pay',
        name: 'pay',
        component: () => import('../views/Member/components/pay.vue')
      },
      {
        path: '/pay/callback',
        name: 'payCallback',
        component: () => import(/* webpackChunkName: "about" */ '../views/Member/components/payCallback')
      }
    ]
  },
  {
    path: '/playground',
    name: 'playground',
    component: () => import(/* webpackChunkName: "about" */ '../views/Playground')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Login')
  },
  {
    path: '/login/callback',
    name: 'callback',
    component: () => import(/* webpackChunkName: "about" */ '../views/Login/callback')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 全局路由守卫
router.beforeEach(function (to, from, next) {
  // console.log(to)
  const token = store.state.user.profile.token
  // 若果要去的页面时vip中的某一个页面，要检查token
  if (to.path.startsWith('/member')) {
    if (token) {
      next()
    } else {
      // 否则跳转到登录页面(登录页面后边加上用户要访问的地方，为登录之后跳转提供地址，在$route.query中可以拿到) 这里的fullpath比path多了参数的字符串
      // 因为浏览器转译时转译不了 & 符号 所以用到encodeURIComponent方法来转译（否则会丢参数）
      next('/login?return_url=' + encodeURIComponent(to.fullPath))
    }
  } else if (token && to.path === '/login') {
    // 已经登录，就不能访问login页面，强制跳转到主页
    next('/')
  } else {
    // 若跳转的不是vip页面就放行
    next() // 这个next很重要，莫要忘了写
  }
})

export default router
